package yiran.itemuse;

import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import yiran.itemuse.output.Logger;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class ConfigManager {
    private static JavaPlugin plugin;
    private static YamlConfiguration mainConfig;

    public static void init(JavaPlugin pluginInstance) {
        plugin = pluginInstance;
        createPluginFolder();
        loadMainConfig();
    }

    private static void createPluginFolder() {
        if (!plugin.getDataFolder().exists()) {
            plugin.getDataFolder().mkdirs();
        }
    }

    public static void loadMainConfig() {
        // 确保主配置文件存在
        File mainConfigFile = new File(plugin.getDataFolder(), "config.yml");
        if (!mainConfigFile.exists()) {
            try (InputStream in = plugin.getResource("config.yml")) {
                if (in != null) {
                    Files.copy(in, mainConfigFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                }
            } catch (IOException e) {
                Logger.error("§c§l无法创建config.yml配置文件: " + e.getMessage());
            }
        }

        // 加载主配置
        mainConfig = YamlConfiguration.loadConfiguration(mainConfigFile);
    }

    public static String getDatabaseType() {
        return mainConfig.getString("database.type", "sqlite");
    }

    public static String getSQLitePath() {
        String filename = mainConfig.getString("database.sqlite.filename", "items.db");
        return new File(plugin.getDataFolder(), filename).getAbsolutePath();
    }

    public static String getMySQLHost() {
        return mainConfig.getString("database.mysql.host", "localhost");
    }

    public static int getMySQLPort() {
        return mainConfig.getInt("database.mysql.port", 3306);
    }

    public static String getMySQLDatabase() {
        return mainConfig.getString("database.mysql.database", "mc_plugin");
    }

    public static String getMySQLUser() {
        return mainConfig.getString("database.mysql.user", "root");
    }

    public static String getMySQLPassword() {
        return mainConfig.getString("database.mysql.password", "");
    }
}
